
#include "conversationconector.h"

ConversationConector::ConversationConector(QTcpSocket *socket)
{
    this->socket = socket;
    this->buffer = NULL;
}

void ConversationConector::CloseConnection()
{
    this->socket->close();
}

ConversationConector::~ConversationConector()
{
}

bool ConversationConector::isActive()
{
    return (this->socket->state() == QAbstractSocket::ConnectedState);
}

//It is called from the TCP socket. Reads all the data in the TCP socket buffer and concatenates it in it's own buffer.
void ConversationConector::dataReception() {
    if (this->socket->bytesAvailable() > 0) {
        QByteArray subBuffer = this->socket->readAll();
        if (this->buffer == NULL) {
            this->buffer = new QByteArray(subBuffer);
        } else {
            this->buffer->append(subBuffer);
        }
    }
}

//Sends packet throught the socket.
int ConversationConector::sendPacket(Packet *packet) {
    QByteArray header = packet->getHeader();
    QByteArray body = packet->getBody();
    int tries = 0;
    int written = 0;
    while (written < header.size()) {
        header.remove(0, written);
        written = this->socket->write(header);
        if (tries++ > 200) return -1;
    }
    tries = 0;
    written = 0;
    while (written < body.size()) {
        body.remove(0, written);
        written = this->socket->write(body);
        if (tries++ > 200) return -1;
    }
    return 0;
}

//Decodes the first full packet from the buffer. Returns null if there isn't one.
Packet *ConversationConector::getPacket() {
    return Packet::readPacket(this->buffer);
}

